const SearchTree = (hook, { SlotTree, Input }) => {
	const { $native } = hook.$m;

	const coloring = (strTitle, searchValue) => {
		const index = strTitle.indexOf(searchValue);
		const beforeStr = strTitle.substring(0, index);
		const afterStr = strTitle.slice(index + searchValue.length);

		return index > -1 ? $native({
			is: 'b',
			children: [beforeStr,
				{
					is: 'span',
					children: searchValue,
					style: { color: '#FF6666' }
				},
				afterStr
			]
		}) : strTitle;
	}

	const filterTreeData = (data, searchText) => {
		return data?.map((item) => {
			let { children, title, ...result } = item;
			// 存在 children
			if (Array.isArray(children) && children.length) {
				let childs = filterTreeData(children, searchText).filter((val) => val);
				if (childs.length) {
					// 所有条件均满足
					result.title = title;
					result.children = childs;
				} else {
					if (title.includes(searchText)) {
						// 当前层级满足，子项不满足
						result.title = coloring(title, searchText);
					} else {
						// 所有条件均不满足
						return;
					}
				}
			} else if (title.includes(searchText)) {
				// 不存在 children 返回原对象
				result.title = coloring(title, searchText);
			} else {
				// 所有条件均不满足
				return;
			}
			return result;
		});
	}

	// ==============================================================================
	return {
		isJiess: true,
		name: 'SearchTree',
		setup({ midder, onSelect, onExpand, ...args }) {
			this.add({
				is: SlotTree,
				$slots: {
					header() {
						return {
							is: Input.Search,
							style: { marginBottom: '8px' },
							placeholder: '筛选',
							onChange: (e) => {
								const { value } = e.target;
								if (value) {
									const dd = filterTreeData(midder.defaultData, value);
									if (dd.filter((val) => val).length) midder.tree.treeData = dd;
								} else {
									midder.tree.treeData = midder.defaultData;
								}
							},
						};
					},
				},
				midder,
				onSelect,
				onExpand,
				...args,
			});
		},
	};
}
export default SearchTree